local skel = fk.CreateSkill {
  name = "efengqi__xinsheng",
}

Fk:loadTranslationTable{
  ["efengqi__xinsheng"] = "新生",
  [":efengqi__xinsheng"] = "每回合结束时，你将“魂”补至2张，若你未获得，你可重铸任意张。",

  ["#efengqi__xinsheng-recast"] = "新生：你可以重铸任意张“魂”",

  ["$efengqi__xinsheng1"] = "幻幻无穷，生生不息。",
  ["$efengqi__xinsheng2"] = "吐故纳新，师法天地。",
}

---@param player ServerPlayer
local addHuashenSkill = function(player, skillName)
  local room = player.room
  local skill = Fk.skills[skillName]
  if (not skill) or player:hasSkill(skill, true) or skill:getSkeleton() == nil or
   (skill:hasTag(Skill.Lord) and player.role ~= "lord")
    or (skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom))
    or skill:isInstanceOf(StatusSkill) -- 纯状态技也不许拿，无法发动
  then
    return
  end

  local huashen_skills = player:getTableMark("efengqi__soul_skills")
  table.insert(huashen_skills, skillName)
  room:setPlayerMark(player, "efengqi__soul_skills", huashen_skills)

  room:addSkill(skill) -- 把附加的状态技添加到房间
  player:addFakeSkill(skill)
  player:prelightSkill(skill.name, true)
  skill:getSkeleton():onAcquire(player, false)
end

---@param player ServerPlayer
local removeHuashenSkill = function(player, skillName)
  local room = player.room
  local skill = Fk.skills[skillName]

  local huashen_skills = player:getTableMark("efengqi__soul_skills")
  if huashen_skills == 0 then return end
  if not table.contains(huashen_skills, skillName) then
    return
  end
  table.removeOne(huashen_skills, skillName)
  room:setPlayerMark(player, "efengqi__soul_skills", huashen_skills)

  player:loseFakeSkill(skill)
  if skill:getSkeleton() then
    skill:getSkeleton():onLose(player, false)
  end
  player:setSkillUseHistory(skillName, 0, Player.HistoryPhase)
  player:setSkillUseHistory(skillName, 0, Player.HistoryTurn)
  player:setSkillUseHistory(skillName, 0, Player.HistoryRound)
  player:setSkillUseHistory(skillName, 0, Player.HistoryGame)
end

--- 添加化身武将牌
---@param player ServerPlayer
---@param general General
local function addHuashen(player, general)
  local room = player.room
  local glist = player:getTableMark("@&efengqi__soul")
  table.insertIfNeed(glist, general.name)
  room:setPlayerMark(player, "@&efengqi__soul", glist)

  for _, s in ipairs(general:getSkillNameList(true)) do
    addHuashenSkill(player, s)
  end
end

--- 移除化身武将牌
---@param player ServerPlayer
---@param general_name string
local function removeHuashen(player, general_name)
  local room = player.room
  local glist = player:getMark("@&efengqi__soul")
  if glist == 0 then return end
  table.removeOne(glist, general_name)
  room:setPlayerMark(player, "@&efengqi__soul", #glist > 0 and glist or 0)

  local general = Fk.generals[general_name]
  for _, s in ipairs(general:getSkillNameList(true)) do
    removeHuashenSkill(player, s)
  end
end

local banned_huashen = {
  "starsp__xiahoudun",  -- 原因：无敌
  "shichangshi",   -- 原因：变将与休整
  "godjiaxu", "zhangfei","rmt__huangzhong", "liyixiejing", "olz__wangyun", "yanyan", "duanjiong", "wolongfengchu", "wuanguo",
  "os__wangling", -- 原因：没有可用技能
  "os__xia__liubei", -- 原因：发动技能逻辑缺陷
}

--- 获得数个“魂”
---@param player ServerPlayer
local function getNewSoul (player, n)
  if n < 1 then return end
  local room = player.room
  local exclude_list = table.map(room.players, function(p)
    return p.general
  end)
  for _, p in ipairs(room.players) do
    if p.deputyGeneral ~= "" then
      table.insert(exclude_list, p.deputyGeneral)
    end
  end
  table.insertTable(exclude_list, banned_huashen)
  local generals = table.filter(room.general_pile, function (g)
    return not table.contains(exclude_list, g)
  end)
  if #generals == 0 then return end
  for _, g in ipairs(table.random(generals, n)) do
    addHuashen(player, Fk.generals[g])
  end
end

skel:addEffect(fk.TurnEnd, {
  can_trigger = function(self, _, target, player, data)
    return player:hasSkill(skel.name) and player:hasSkill("efengqi__huashen", true)
  end,
  on_cost = function (self, event, target, player, data)
    if #player:getTableMark("@&efengqi__soul") < 2 then
      return true
    else
      local result = player.room:askToCustomDialog(player, {
        skill_name = skel.name, qml_path = "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", extra_data = {
          player:getTableMark("@&efengqi__soul"),
          {"OK"},
          "#efengqi__xinsheng-recast",
          {"Cancel"},
          1,
          999
        }
      })
      if result ~= "" then
        local reply = json.decode(result)
        event:setCostData(self, reply.cards)
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = 0
    local removed = event:getCostData(self) or {}
    if #removed > 0 then
      for _, g in ipairs(removed) do
        removeHuashen(player, g)
      end
      n = #removed
    else
      n = 2 - #player:getTableMark("@&efengqi__soul")
    end
    getNewSoul(player, n)
  end,
})



return skel
